package com.hyt.it.ogt.kq.common.gov.utils.tree;

import java.util.ArrayList;
import java.util.List;

/**
 * 树工具类
 *
 * @author liuq
 * @since 2020-12-22
 */
public class TreeUtil {
	
    public static List<Tree> treeToMultilevel(List<Tree> trees) {
    	Boolean loop = true;
    	while (loop) {
    		loop = false;
    		for (int i = trees.size() - 1; i >= 0; i--) {
    			String pid = trees.get(i).getPid();
    			if (pid != null) {

					String id = trees.get(i).getValue();
    				int pIndex = -1;
    				Boolean noSon = true;
    				for (int j = 0; j < trees.size(); j++) {
    					if (trees.get(j).getPid() != null && trees.get(j).getPid().equals(id)) {
    						noSon = false;
    						break;
    					}
    					if (trees.get(j).getValue().equals(pid)) {
    						pIndex = j;
    					}
    				}
    				if (noSon) {
    					if (pIndex >= 0) {
    						if (trees.get(pIndex).getChildren() == null) {
    							List<Tree> children = new ArrayList<Tree>();
    							trees.get(pIndex).setChildren(children);
    						}
    						trees.get(pIndex).getChildren().add(0, trees.get(i));
    						trees.remove(i);
    					}
    				} else {
    					loop = true;
    				}
				}
    		}
		}
    	return trees;
    }

}
